<template>
  <a-tree
    class="q-tree"
    :show-line="true"
    v-model:expandedKeys="expandedKeys"
    v-model:selectedKeys="selectedKeys"
    @select="select"
    @expand="expand"
    :loadData="onLoadData"
    :tree-data="treData"
  />
</template>

<script>

export default {
  name: 'QTree',
  props : {
    treeData: {
      type:Array,
      required: false,
      default: function() {
        return []
      }
    },
    asyncLoad: {
      type:Boolean,
      required: false,
      default: false
    }
  },
  data () {
    return {
      selectedKeys: [],
      expandedKeys: [],
      treData: [...this.treeData]
    }
  },
  methods : {
    onLoadData (treeNode) {
      const that = this
      return new Promise(resolve => {
        if (that.asyncLoad) {
          that.$emit('loadData', treeNode, data => {
            if (data.length === 0)  {
              resolve();
              return;
            }
            treeNode.dataRef.children = data.map((item) => {
              return item
            })
            that.treData = [...that.treData];
            resolve();
          })
        } else {
          resolve()
        }
      });
    },
    select() {
      this.$emit('select',this.selectedKeys)
    },
    expand() {
      this.$emit('expand',this.expandedKeys)
    }
  }
};
</script>

<style lang="less" scoped>
  :deep(.q-tree){
    .ant-tree .ant-tree-treenode{
      width: 100%;
    }
  }
</style>
